import axios from "axios";
import type { AxiosResponse } from "axios";
import { ElMessage } from "element-plus";

// 定义通用响应结构
export interface ApiResponse<T> {
  code: number;
  data: T;
  message: string;
}

// 创建一个 Axios 实例
const axiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 30000,
});

// 定义请求拦截器
axiosInstance.interceptors.request.use(
  (config: any) => {
    // 设置token
    config.headers['Access-Control-Allow-Origin'] = '*'
    config.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
    config.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 定义响应拦截器
axiosInstance.interceptors.response.use(
  (response: any) => {

    // 判断状态码
    if (response.status !== 200) {
      ElMessage.error(response.data.msg || "请求失败，请稍后重试");
      return
    }

    // 判断返回的是json数据还是字节流文件
    return response
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

export default axiosInstance;
